package com.lanhao.aot.carrierintegration.usps;

import java.io.File;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.lanhao.aot.carrierintegration.AeIfRequestDTO;
import com.lanhao.aot.carrierintegration.Warehouse;
import com.lanhao.aot.util.Dom4jUtil;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;

public class UspsReturnUtil {
	public static final Logger LOG = LoggerFactory.getLogger(UspsReturnUtil.class);
	public static final String SERVICE_CODE = "020";
	public static final String TEMPLATE_SIZE = "Zebra-4X6";
	public static final String LABEL_FORMAT = "NOI";
	public static final String FILE_TYPE = "PDF";
	public static final String COUNTRY_CODE = "US";
	
	public static final String WEST_WAREHOUSE = "CKUSSM0001";
	public static final String EAST_WAREHOUSE = "CKUSBH0001";

	public static void main(String[] args) {
		AeIfRequestDTO request = new AeIfRequestDTO();
		Warehouse warehouse = new Warehouse();
		request.setCountry_code(COUNTRY_CODE);
		request.setShipper_country_code(COUNTRY_CODE);
		
//		warehouse.setReceiver("KunKun-W");
//		request.setShipper_city("LOS ANGELES");
//		request.setShipper_name("Victor Lee");
//		request.setShipper_phone("(646) 289-2662");
//		request.setShipper_post_code("90028");
//		request.setShipper_province("California");
//		request.setShipper_street("1558 GORDON ST APT 302");
//		request.setWarehouse_code(WEST_WAREHOUSE);
		
		warehouse.setReceiver("KunKun-E");
		request.setShipper_city("Quincy");
		request.setShipper_name("USshopper");
		request.setShipper_phone("637772095");
		request.setShipper_post_code("32351");
		request.setShipper_province("Florida");
		request.setShipper_street("Quincy, Florida, 5138BenBostickRd");
		request.setWarehouse_code(EAST_WAREHOUSE);
		
		createOrder(request, warehouse);
	}

	public static void createOrder(AeIfRequestDTO request, Warehouse warehouse) {
		try {
			Pair<String, String> param = getShipmentParemeterByWareHouse(request.getWarehouse_code());
			String sendAccount = param.getLeft();
			String mId = param.getRight();
			String street = request.getShipper_street();
			String shipper_name = request.getShipper_name();
			if (shipper_name.length() > 30) {
				shipper_name = shipper_name.substring(0, 30);
			}
			String senderAddress = street;
			String senderAddress2 = StringUtils.EMPTY;
			if (street.length() > 30) {
				senderAddress = street.substring(0, 30);
				senderAddress2 = street.substring(30);
				if (senderAddress2.length() > 30) {
					senderAddress2 = senderAddress2.substring(0, 30);
				}
			}
			String zipCode = StringUtils.isBlank(request.getShipper_post_code())
					|| request.getShipper_post_code().length() != 5 ? "11111" : request.getShipper_post_code();

			StringBuilder result = new StringBuilder();
			result.append("<ExternalReturnLabelRequest>");
			result.append("<CustomerName>").append(shipper_name).append("</CustomerName>"); // 客户名 Chris Brown
			result.append("<CustomerAddress1>").append(senderAddress).append("</CustomerAddress1>"); // 客户地址
			result.append("<CustomerAddress2>").append(senderAddress2).append("</CustomerAddress2>"); // 客户地址2
			result.append("<CustomerCity>").append(request.getShipper_city()).append("</CustomerCity>"); // 客户城市
			result.append("<CustomerState>").append(request.getShipper_province()).append("</CustomerState>"); // 客户所在州

			result.append("<CustomerZipCode>").append(zipCode).append("</CustomerZipCode>"); // 客户邮编 20024
//			result.append("<MerchantAccountID>").append(order.getSendSite()).append("</MerchantAccountID>"); // 客户AccountID
			result.append("<MerchantAccountCode>").append(sendAccount).append("</MerchantAccountCode>"); // 客户MerchantAccountCode
			result.append("<MID>").append(mId).append("</MID>"); // 客户ID
			/**
			 *
			 * * TemplateSize=4x6 * TemplateSize=Zebra-4X6 * TemplateSize=4x4 *
			 * TemplateSize=3x6
			 *
			 */
			result.append("<LabelDefinition>").append(TEMPLATE_SIZE).append("</LabelDefinition>"); // 模板标签大小
			result.append("<LabelFormat>").append(LABEL_FORMAT).append("</LabelFormat>"); // 模板类型
			/**
			 * 必填 在商户配置文件设置中指定的标签的服务类型。*请注意，列出的服务类型代码自2011年12月2日起是新的；Web服务将不再接受使用旧STC的呼叫。
			 * enumerations:  044 (Parcel Return 包裹退回服務 Service)  019 (Priority Mail
			 * 优先邮件退货服务 Returns® service)  596 (Priority Mail Returns 优先邮件退回服务、保险<=200美元 ®
			 * service, Insurance <= $200)  020 (First-Class Package 头等舱包装退货服务 Return ®
			 * service)  597 (First-Class Package 头等舱包装返回®服务，保险<=200美元 Return® service,
			 * Insurance <= $200)  022 (Ground Return 接地回路服务 Service)  024 (PRS – Full
			 * Network) PRS–全网络  017 (PRS – Full Network, PRS–全网络，保险<=200美元 Insurance
			 * <=$200)  018 (PRS – Full Network, PRS–全网络，保险费>200美元 Insurance >$200)
			 */
			result.append("<ServiceTypeCode>").append(SERVICE_CODE).append("</ServiceTypeCode>"); // 服务code
			result.append("<CompanyName>").append("").append("</CompanyName>"); // 公司名称
			result.append("<MerchandiseDescription>").append("").append("</MerchandiseDescription>"); //

			result.append("<AddressOverrideNotification>").append(true).append("</AddressOverrideNotification>"); //
			result.append("<CallCenterOrSelfService>").append("Customer").append("</CallCenterOrSelfService>"); // 客户名
																												// Chris
			// Brown

			result.append("<ImageType>").append(FILE_TYPE).append("</ImageType>"); // 面签类型
			result.append("<SenderName>").append(shipper_name).append("</SenderName>"); // 发件人名字
			result.append("<SenderEmail>").append("").append("</SenderEmail>"); // 发件人邮编

			result.append("<RecipientName>").append(warehouse.getReceiver()).append("</RecipientName>"); // 收件人名字
			result.append("<RecipientEmail>").append("").append("</RecipientEmail>"); // 收件人邮编
			boolean isBlankLabel = false;
			if (isBlankLabel) {
				result.append("<BlankCustomerAddress>").append(isBlankLabel).append("</BlankCustomerAddress>"); // 是否生成空白面单
			}
			result.append("</ExternalReturnLabelRequest>");

			String fileType = "PDF";
			String assmbelyParam = result.toString().replaceAll("\\+", "%2B").replaceAll("&", "&amp;");
			LOG.info("请求USPS组装原始参数assmbelyParam={}", assmbelyParam);
			String xml = java.net.URLEncoder.encode(assmbelyParam, "UTF-8");
			String requestUrl = "https://returns.usps.com/services/GetLabel?externalReturnLabelRequest=" + xml;
			LOG.info("开始向USPS请求信息url={}", requestUrl);
			String respBody = HttpRequest.get(requestUrl).timeout(10000).execute().body();
			LOG.info("[{}]USPS返回结果result={}", respBody);
			// 发送请求
			Document doc = DocumentHelper.parseText(respBody);
			// 返回参数进行组装
			JSONObject json = new JSONObject();
			Dom4jUtil.dom4j2Json(doc.getRootElement(), json);
			LOG.info("USPS返回xml报文转json的结果result={}", json.toString());
			// 成功返回，ReturnLabel是标签 TrackingNumber是运单号
			String printTemplate = json.getString("ReturnLabel");
			if (StringUtils.isNotBlank(printTemplate)) {
				String trackingNumber = json.getString("TrackingNumber");
//				String postalRouting = json.getString("PostalRouting");
				String carrier = "USPS";
				String fileName = carrier + "_" + trackingNumber + "." + fileType.toLowerCase();
				Base64.decodeToFile(printTemplate, new File("D:/" + fileName));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据仓库获取东西部账号信息
	 * 
	 * @param warehouseCode
	 * @return
	 */
	public static Pair<String, String> getShipmentParemeterByWareHouse(String warehouseCode) {
//		if (WEST_WAREHOUSE.equals(warehouseCode)) {
//			return Pair.of("BA5261CC68954132814D9BDD4BF83721", "902567547");
//		}
//		return Pair.of("771DA634D18E4D529B2A4F2F74748F02", "902572732");
		
		if (WEST_WAREHOUSE.equals(warehouseCode)) {
			return Pair.of("CDA428BC86C34A12B5F9B0F553772CF7", "903574123"); // 西边
		}
		return Pair.of("C16AF6A4EF3A476985A35AD3F605C3D4", "903574120"); // 东边
	}
}
